import OpenIMSDKRN, {OpenIMEmitter} from "open-im-sdk-rn";
import RNFS from "react-native-fs";
import { Platform } from "react-native";
import { getApiUrl, getWsUrl } from "@/config"
import { useConversationStore } from "@/hooks/im/conversation"
import { MessageItem, ConversationItem } from "open-im-sdk-rn/lib/typescript/types/entity";
import { v4 as uuidv4 } from "uuid";
import dayjs from "dayjs";
import calendar from "dayjs/plugin/calendar";
import relativeTime from "dayjs/plugin/relativeTime";
import updateLocale from "dayjs/plugin/updateLocale";
import zhCn from "dayjs/locale/zh-cn";
import { GroupSessionTypes, GroupSystemMessageTypes, MessageType, SessionType } from "@/constants/ImContants";
import {useGlobalEvent} from "@/hooks/im/useGlobalEvent";
import {useSelector} from "react-redux";
import {RootState} from "@/store";


// console.log("zhCn", zhCn);


dayjs.extend(calendar);
dayjs.extend(relativeTime);
dayjs.extend(updateLocale);

dayjs.updateLocale("en", {
    calendar: {
        sameDay: "HH:mm",
        nextDay: "[明天]",
        nextWeek: "dddd",
        lastDay: "[昨天] HH:mm",
        lastWeek: "dddd HH:mm",
        sameElse: "YYYY年M月D日 HH:mm",
    },
});
dayjs.updateLocale("zh-cn", {
    calendar: {
        sameDay: "H:mm",
        nextDay: "[明天] H:mm",
        nextWeek: "dddd",
        lastDay: "[昨天] H:mm",
        lastWeek: "dddd HH:mm",
        sameElse: "YYYY年M月D日 HH:mm",
    },
});
dayjs.locale(zhCn);


export const platformID = Platform.OS === "ios" ? 1 : 2;

export const initStore = () => {
    const { getConversationListByReq } = useConversationStore.getState();
    getConversationListByReq();
};

export const initSDK = (IMUserID, IMToken) => {
    RNFS.mkdir(`${RNFS.DocumentDirectoryPath}/tmp`);
    OpenIMSDKRN.initSDK(
        {
            platformID,
            apiAddr: getApiUrl(),
            wsAddr: getWsUrl(),
            dataDir: `${RNFS.DocumentDirectoryPath}/tmp`,
            logLevel: 5,
            isLogStandardOutput: true,
        },
        uuidv4(),
    )
        .then(async () => {
            console.log(`initSDK success, platformID: ${platformID}`);
            OpenIMSDKRN.getLoginStatus(uuidv4())
                .then(async (data) => {
                    if (data == 3) {
                        initStore();
                    } else if (data == 1) {
                        OpenIMSDKRN.login(
                            {
                                userID: IMUserID as string,
                                token: IMToken as string,
                            },
                            uuidv4(),
                        ).then(res => {
                            OpenIMEmitter.addListener('onConnecting', () => {
                                console.log('onConnecting');
                            });

                            OpenIMEmitter.addListener('onConnectSuccess', () => {
                                initStore();
                            });

                            OpenIMEmitter.addListener('onConnectFailed', ({ errCode, errMsg }) => {
                                console.log('onConnectFailed', errCode, errMsg);
                            });
                        })
                            .catch(err => {
                                console.log('err', err);
                            })
                    };
                })
                .catch(({ errCode, errMsg }) => {
                    // 调用失败
                });
        })
        .catch((error) => {
            console.log("initSDK error", error);
        });
};


export const formatMessageByType = (message: MessageItem): string => {
    switch (message.contentType) {
        case MessageType.TextMessage:
            return message.textElem?.content;
        default:
            return "";
    }
};

export const formatConversionTime = (timestemp: number): string => {
    if (!timestemp) return "";

    const fromNowStr = dayjs(timestemp).fromNow();

    return fromNowStr;
};


export const getConversationContent = (message: MessageItem, uid) => {
    const selfInfo ={ userID: uid };
    if (
        !message.groupID ||
        GroupSystemMessageTypes.includes(message.contentType) ||
        message.sendID === selfInfo.userID ||
        message.contentType === MessageType.GroupAnnouncementUpdated
    ) {
        return formatMessageByType(message);
    }
    return `${message.senderNickname}：${formatMessageByType(message)}`;
};

export const conversationSort = (conversationList: ConversationItem[] = []) => {
    const arr: string[] = [];
    const filterArr = conversationList.filter((c) => !arr.includes(c.conversationID) && arr.push(c.conversationID));
    filterArr.sort((a, b) => {
        if (a.isPinned === b.isPinned) {
            const aCompare = a.draftTextTime > a.latestMsgSendTime ? a.draftTextTime : a.latestMsgSendTime;
            const bCompare = b.draftTextTime > b.latestMsgSendTime ? b.draftTextTime : b.latestMsgSendTime;
            if (aCompare > bCompare) {
                return -1;
            }
            if (aCompare < bCompare) {
                return 1;
            }
            return 0;
        }
        if (a.isPinned && !b.isPinned) {
            return -1;
        }
        return 1;
    });
    return filterArr;
};

export const isGroupSession = (sessionType?: SessionType) => (sessionType ? GroupSessionTypes.includes(sessionType) : false);

